package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.comment.response.JsonResult;
import cn.tedu._05weibo.comment.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.List;


@Api(tags = "02.微博管理模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;


    /**
     * 5.添加微博
     *
     * @param weiboDTO
     * @param session
     * @return
     */
    @ApiOperation(value ="5.添加微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        log.debug("weiboDTO = " + weiboDTO);
        // 校验登录状态
        UserVO userVO = (UserVO) session.getAttribute("user");
        // 判断是否登录 ==null 未登录
        if (userVO == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        //插入微博
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insert(weibo);
        return new JsonResult(StatusCode.LOGIN_SUCCESS);
    }


    /**
     * 6.首页微博列表功能
     */
    @ApiOperation(value ="6.首页微博列表功能")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        //return new JsonResult(StatusCode.OPERATION_SUCCESS,weiboMapper.selectIndex());
        return JsonResult.success(weiboMapper.selectIndex());
    }

    /**
     * 7.微博详情功能
     */
    @ApiOperation(value ="7.微博详情功能")
    @GetMapping("selectById")
    @ApiImplicitParam(name = "id", value = "微博编号",required = true,dataType = "int")
    @Validated
    public JsonResult selectById(@Range(min = 200,max = 300,message = "微博编号在200-300之间") @RequestParam(value = "id") Integer id) throws IllegalAccessException {
        //强行抛异常
        if (id < 0) {
            throw new IllegalAccessException("测试异常,id值不能小于0");
        }
        //return new JsonResult(StatusCode.OPERATION_SUCCESS,weiboMapper.selectById(id));
        return JsonResult.success(weiboMapper.selectById(id));
    }
}
